package com.zy.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.*;

/**
 * @author zhangyi
 * @date 2018/7/21 15:16
 */
@Service
public class FileService {
    /**
     * 保存文件路径
     */
    @Value("${fileConfig.filePath}")
    private String filePath;

    /**
     * 每个客户端连接后，生成唯一的表示符文件
     *
     * @param string
     * @param fileUniquelyIdentifies
     * @throws Exception
     */
    public void saveData(String string,String fileUniquelyIdentifies) throws Exception{

        //需要保存的路径(将每个客户端连接的文件分类存储)
        File file = new File(filePath+File.separator+fileUniquelyIdentifies+".ooo");
        if(!file.exists()){
            file.createNewFile();
        }
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
        bufferedWriter.write(string);
        bufferedWriter.flush();
        bufferedWriter.close();
    }
    public String readData(){
        File file = new File(filePath);
        File[] files = file.listFiles();
        StringBuffer stringBuffer = new StringBuffer();
        for(File fileName : files){
                if (fileName.isFile() && fileName.getName().substring(fileName.getName().indexOf(".")).equals(".ooo")) {
                    //区分读取文件信息
                    stringBuffer.append(fileName.getName()+"=");
                    try {
                        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName.getAbsoluteFile())));
                        String str = "";
                        while((str = bufferedReader.readLine())!= null){
                            stringBuffer.append(str);
                            System.out.println(stringBuffer.toString());
                        }
                    }catch (Exception e){
                        throw new RuntimeException("文件读取错误！");
                    }
                }
        }
        return stringBuffer.toString();
    }
}
